import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
  HttpStatus,
} from '@nestjs/common';
import { catchError, map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
  data: T;
}
@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map(data => {
        let dataTemp: any = data
        let errorStatus = [HttpStatus.INTERNAL_SERVER_ERROR,HttpStatus.UNAUTHORIZED]
        if(errorStatus.indexOf(dataTemp?.status) > -1){
          let message = dataTemp.message
          if(message?.toString().indexOf('Error:') > -1){
            message = message.replace(/Error:/g,'系统错误:')
          }
          return {
            data,
            code: dataTemp.status,
            message: message,
          };
        }
        else{
          return {
            data,
            code: 0,
            message: '请求成功',
          };
        }
      })
    );
  }
}
